package edu.hawaii.ics.pjdb.worker.command_runners;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import edu.hawaii.ics.pjdb.result_transport.TupleServiceHelper;
import edu.hawaii.ics.pjdb.types.CsvSourceCommand;
import edu.hawaii.ics.pjdb.types.WorkerCommand;

public class CsvSourceRunner extends CommandRunner {
    private static final Logger logger = LoggerFactory
            .getLogger(CsvSourceRunner.class);

    public CsvSourceRunner(Connection localDb) {
        super(localDb);
    }

    @Override
    public void execute(WorkerCommand cmd) throws SQLException, TException {
        CsvSourceCommand csvCmd = cmd.getCommand().getCsvSourceCmd();
        logger.info("Getting tuples from \"{}\", sending output to {}",
                csvCmd.getCsvFile(), cmd.getOutputAddress());
        try {

            // Read from the CSV file and send the tuples to the output stream.
            TupleServiceHelper.submitTuples(cmd.getOutputAddress(),
                    csvCmd.getCsvFile(), csvCmd.isHeader());
        } catch (FileNotFoundException e) {
            logger.info("Error: Could not find CSV file \"{}\"",
                    csvCmd.getCsvFile());
        } catch (IOException e) {
            logger.info("Error: I/O problem occurred when reading from CSV file.");
        }
    }
}